package com.xjgc.common;

import java.io.*;

/**
 * @author: 小逗号
 * @date: 2023-11-7
 * @description:
 * @since:
 */
public class MsiClassLoader extends ClassLoader {
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return super.loadClass(name);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String dir = MsiClassLoader.class.getResource("/").getPath();
        String classFile = dir + name.replace(".", "/") + ".class";
        File file = new File(classFile);

        FileInputStream fileInputStream = null;
        try {
            byte[] bytes = new byte[1024];
            fileInputStream = new FileInputStream(file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int temp = -1;
            while ((temp = fileInputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, temp);
            }
            byte[] result = byteArrayOutputStream.toByteArray();
            Class<?> aClass = defineClass(null, result, 0, result.length);
            return aClass;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return super.findClass(name);
    }
}
